package org.example.day03;

/**
 *  第二章节2.1.4.1:同一对象锁可以锁不同的方法.
 **/
public class MyThread6 {
    //①两个方法都被synchronized修饰，对象锁如果是同一个对象，则这俩方法得串行执行。
    synchronized public void methodA(){
        try {
            System.out.println(this);
            System.out.println("begin methodA, threadName = " + Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println("endTime A = " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    synchronized public void methodB(){
        try {
            System.out.println(this);
            System.out.println("begin methodB, threadName = " + Thread.currentThread().getName());
            System.out.println("begin time = " + System.currentTimeMillis());
            Thread.sleep(5000);
            System.out.println("endTime B = " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread6 m6 = new MyThread6();
        Thread6A a = new Thread6A(m6);
        a.setName("A");
        Thread6B b = new Thread6B(m6);
        b.setName("B");
        a.start();
        b.start();
    }
}

class Thread6A extends Thread{
    private MyThread6 m6;

    public Thread6A(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.methodA();
    }
}

class Thread6B extends Thread{
    private MyThread6 m6;

    public Thread6B(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.methodB();
    }
}
